package com.tanjun.publicservice.web.service.impl;

import com.tanjun.common.enums.FileTypeEnum;
import com.tanjun.common.exception.BizException;
import com.tanjun.publicservice.web.exceptions.FileErrCode;
import com.tanjun.publicservice.web.service.UploadFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
@Primary
public class LocalUploadFileService implements UploadFileService {
    @Value("${file.upload-dir:''}")
    private String uploadDir;

    /**
     * 上传文件
     *
     * @param file         文件内容
     * @param fileTypeEnum 文件类型
     * @return 文件保存路径
     */
    @Override
    public String upload(MultipartFile file, FileTypeEnum fileTypeEnum) {
        checkFile(file, fileTypeEnum);
        String fileName = generateFileName(file.getOriginalFilename());
        File saveFile = new File(uploadDir + File.pathSeparator + fileName);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            throw new BizException(FileErrCode.FILE_ERR);
        }
        return "static/" + fileName;
    }

    /**
     * 删除文件
     *
     * @param fileNames 文件名称
     * @return 是否删除成功
     */
    @Override
    public boolean delFiles(List<String> fileNames) {
        return false;
    }
}
